package com.xgc.book.bookserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgc.book.bookserver.bean.BookCatalogBean;
import com.xgc.book.bookserver.bean.RecordBean;
import com.xgc.book.bookserver.mapper.RecordMapper;
import com.xgc.book.bookserver.service.BookCatalogService;
import com.xgc.book.bookserver.service.RecordService;
import com.xgc.book.bookserver.util.ResultJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 阅读记录表 服务实现类
 * </p>
 *
 * @author wrz
 * @since 2023-11-20
 */
@Service
@Transactional
public class RecordServiceImpl extends ServiceImpl<RecordMapper, RecordBean> implements RecordService {
    @Autowired
    private BookCatalogService bookCatalogService;

    @Override
    public RecordBean getRecord(int bookId, int vipId) {
        RecordBean recordBean = this.getOne(new QueryWrapper<RecordBean>()
                .eq("book_id", bookId)
                .eq("vip_id", vipId));
        if (recordBean == null) {
            List<BookCatalogBean> list = bookCatalogService.list(new QueryWrapper<BookCatalogBean>()
                    .eq("book_id", bookId)
                    .orderByAsc("order_no"));
            if (!list.isEmpty()) {
                recordBean = new RecordBean();
                recordBean.setCatalogId(list.get(0).getId());
                recordBean.setBookId(bookId);
                recordBean.setVipId(vipId);
            }
        }
        return recordBean;
    }

    @Override
    public ResultJson savaRecord(RecordBean recordBean) {
        RecordBean record = getRecord(recordBean.getBookId(), recordBean.getVipId());
        if (recordBean.getCatalogId() != null) {
            record.setCatalogId(recordBean.getCatalogId());
        }
        record.setReadTime(new Date());
        this.saveOrUpdate(record);
        return ResultJson.ok();
    }

    @Override
    public ResultJson getPage(int page, int limit, RecordBean recordBean) {
        IPage<RecordBean> iPage = this.page(new Page<>(page, limit), new QueryWrapper<RecordBean>()
                .eq(recordBean.getBookId() != null, "book_id", recordBean.getBookId())
                .eq(recordBean.getVipId() != null, "vip_id", recordBean.getVipId())
                .orderByDesc("read_time"));
        return ResultJson.ok(iPage);
    }
}
